package com.wanpinghui.supplier.business;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.SharedElementCallback;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.connect.UserInfo;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.addrbook.CustomerInfoActivity;
import com.wanpinghui.supplier.business.view.CircleCommentListView;
import com.wanpinghui.supplier.business.view.MultiImageView;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.utils.WTimeUtil;
import com.wanpinghui.supplier.widgets.TitlePanelLayout;
import com.wanpinghui.supplier.widgets.TitlePanelLayoutUser;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.common.RxEventType;
import com.wanpinghui.wphlibrary.common.toast.ToastManager;
import com.wanpinghui.wphlibrary.model.business.BusinessService;
import com.wanpinghui.wphlibrary.model.business.bean.CommentBean;
import com.wanpinghui.wphlibrary.model.business.bean.DynamicBean;
import com.wanpinghui.wphlibrary.model.business.bean.ThumbUpBean;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.yunshl.yunshllibrary.rxbus.RxBus;
import com.yunshl.yunshllibrary.rxbus.SubscriptionBean;
import com.yunshl.yunshllibrary.utils.SoftInputUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;
import com.yunshl.yunshllibrary.view.YunShlPopupWinow;

import org.xutils.common.util.DensityUtil;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.List;
import java.util.Map;

import retrofit.callback.YRequestCallback;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2018/1/29
 ***/
@ContentView(R.layout.layout_activity_dynamic_detail_text)
public class DynamicDetailActivity extends BaseActivity {
    @ViewInject(R.id.iv_avatar)
    private ImageView imageViewAvatar;
    @ViewInject(R.id.tv_user_name)
    private TextView textViewName;
    @ViewInject(R.id.tv_content)
    private TextView textViewContent;
    @ViewInject(R.id.tv_time)
    private TextView textViewTime;
    @ViewInject(R.id.iv_look_user)
    private ImageView imageViewLookPeople;
    @ViewInject(R.id.iv_comment)
    private ImageView imageViewComment;
    @ViewInject(R.id.tv_thumb_up)
    private TextView textViewUpUser;
    @ViewInject(R.id.lv_comments)
    private CircleCommentListView listViewComment;
    @ViewInject(R.id.ll_likes_comments_area)
    private LinearLayout linearLayoutCommentArea;
    @ViewInject(R.id.v_line)
    private View viewLine;
    @ViewInject(R.id.edt_input)
    private EditText editTextInput;
    @ViewInject(R.id.tpl_title)
    private TitlePanelLayoutUser mLayoutTitle;
    @ViewInject(R.id.tv_send)
    private TextView mTextViewSend;
    @ViewInject(R.id.ll_likes_area)
    private LinearLayout mLayoutLikeArea;
    @ViewInject(R.id.iv_image_content)
    private MultiImageView imageViewContent;
    @ViewInject(R.id.tv_visible_count)
    private TextView textViewVisibleCount;
    @ViewInject(R.id.iv_visible_count_bottom)
    private ImageView imageViewVisibleBottom;

    private DynamicBean mDynamicBean;
    private View commentView;
    private YunShlPopupWinow popupWindow;
    private int mToUserId;
    private String mComentText;
    private Bundle mReenterState;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        WPHSdk.getService(OAuthService.class).getUserId();
        if (getIntent() != null) {
            String dataStr = getIntent().getStringExtra("data");
            if (TextUtil.isNotEmpty(dataStr)) {
                mDynamicBean = new Gson().fromJson(dataStr, new TypeToken<DynamicBean>(){}.getType());
            }
        }
    }

    @Override
    public void bindEvents() {
        mLayoutTitle.setOnClickBacktrack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mTextViewSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtil.isNotEmpty(editTextInput.getText().toString())) {
                    String text = editTextInput.getText().toString();
                    commentDynamic(mDynamicBean.getId(), mToUserId, text);
                    editTextInput.setText("");
                    editTextInput.setHint("评论");
                }
            }
        });

        imageViewLookPeople.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (textViewVisibleCount.isShown()) {
                    textViewVisibleCount.setVisibility(View.GONE);
                    imageViewVisibleBottom.setVisibility(View.GONE);
                }else {
                    textViewVisibleCount.setVisibility(View.VISIBLE);
                    imageViewVisibleBottom.setVisibility(View.VISIBLE);
                    if (mDynamicBean.getVisible_type() == 21) {
                       textViewVisibleCount.setText("全国工程商可见，共"+mDynamicBean.getEngineer_quantity()+"人");
                    }else {
                        if (TextUtil.isNotEmpty(mDynamicBean.getArea_names())) {
                            String[] strings = mDynamicBean.getArea_names().split(",");
                            String contentStr = mDynamicBean.getArea_names();
                            if (strings.length > 2) {
                                contentStr = strings[0]+","+strings[1]+","+strings[2]+"...";
                            }
                            textViewVisibleCount.setText(contentStr+"工程商可见，共"+mDynamicBean.getEngineer_quantity()+"人");
                        }
                    }
                }
            }
        });
    }

    @Override
    public void initData() {

        setData();

        textViewName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        imageViewComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCommentWindow(imageViewComment, mDynamicBean.getUser_id(), mDynamicBean.getUserName());
            }
        });
        listViewComment.setListener(new CircleCommentListView.CommonListener() {
            @Override
            public void onCommont(CommentBean bean, int toUserId, String textStr) {
                mToUserId = toUserId;
                int myId = WPHSdk.getService(OAuthService.class).getUserId();
                if (toUserId == myId) {
                    showDeleteDialog(bean.getId());
                }else {
                    editTextInput.setFocusable(true);
                    editTextInput.setFocusableInTouchMode(true);
                    editTextInput.requestFocus();
                    if (toUserId != mDynamicBean.getUser_id()) {
                        editTextInput.setHint("回复"+textStr+":");
                    }else {
                        editTextInput.setHint("评论");
                    }
                    editTextInput.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            editTextInput.setFocusable(true);
                            editTextInput.setFocusableInTouchMode(true);
                            editTextInput.requestFocus();
                            SoftInputUtil.showSoftInput(DynamicDetailActivity.this, editTextInput);
                        }
                    },200);
                }
            }

            @Override
            public void onUser(int userId, String userName) {
                Intent intent = new Intent(DynamicDetailActivity.this, CustomerInfoActivity.class);
                intent.putExtra("user_id", userId);
                startActivity(intent);
            }
        });

    }

    private void setData() {
        textViewName.setText(mDynamicBean.getUserName());
        textViewContent.setText(mDynamicBean.getContent());
        if (mDynamicBean.getCommentCount() == 0 || mDynamicBean.getThumbUpCount() == 0) {
            viewLine.setVisibility(View.GONE);
        }else {
            viewLine.setVisibility(View.VISIBLE);
        }
        if (mDynamicBean.getThumbUpCount() > 0) {
            mLayoutLikeArea.setVisibility(View.VISIBLE);
        }else {
            mLayoutLikeArea.setVisibility(View.GONE);
        }
        textViewUpUser.setText(mDynamicBean.getThumbUpStr());

        if (mDynamicBean.getCommentCount() == 0 && mDynamicBean.getThumbUpCount() == 0) {
            linearLayoutCommentArea.setVisibility(View.GONE);
        }else {
            linearLayoutCommentArea.setVisibility(View.VISIBLE);
        }
        if (mDynamicBean.getCommentCount() > 0) {
            listViewComment.setDatas(mDynamicBean);
        }
        Glide.with(this).load(mDynamicBean.getAvatar()).asBitmap().error(R.mipmap.my_icon_head_default).into(imageViewAvatar);

        if (mDynamicBean.getCreated_at() > 0) {
            textViewTime.setText(WTimeUtil.getTimeShowStr(mDynamicBean.getCreated_at()));
        }else {
            textViewTime.setText("1970-01-01 08:00:00");
        }

        if (mDynamicBean.getContentImgs() != null && mDynamicBean.getContentImgs().size() > 0) {
            imageViewContent.setViewWidth(DensityUtil.getScreenWidth()-DensityUtil.dip2px(87));
            imageViewContent.setDatas(mDynamicBean.getContentImgs());
        }

        if(mDynamicBean.getVisible_type() == 1 || mDynamicBean.getVisible_type() == 11) {
            imageViewLookPeople.setVisibility(View.GONE);
        }else {
            if(WPHSdk.getService(OAuthService.class).getUserId()==mDynamicBean.getUser_id())
                imageViewLookPeople.setVisibility(View.VISIBLE);
            else
                imageViewLookPeople.setVisibility(View.GONE);
        }
    }

    private void showCommentWindow(final View view, int toUserId, String toUserName) {
        mToUserId = toUserId;
        if (commentView == null) {
            commentView = LayoutInflater.from(DynamicDetailActivity.this).inflate(R.layout.view_popupwindow_comment, null);
            popupWindow = new YunShlPopupWinow(commentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            popupWindow.setAnimation(DynamicDetailActivity.this,false, R.style.dialog_right_left_scale_animation);
        }
        LinearLayout linearLayoutComment = (LinearLayout) commentView.findViewById(R.id.ll_comment);
        LinearLayout linearLayoutUp = (LinearLayout) commentView.findViewById(R.id.ll_thumb_up);
        final TextView textView = (TextView) commentView.findViewById(R.id.tv_like_or_cancel);
        if (mDynamicBean.haveILike(WPHSdk.getService(OAuthService.class).getUserId())) {
            textView.setText("取消");
        }else {
            textView.setText("赞");
        }
        if (Build.VERSION.SDK_INT < 24) {
            popupWindow.showAsDropDown(view, -DensityUtil.dip2px(101), -DensityUtil.dip2px(26));
        }else {
            popupWindow.showAsDropDown(view, DensityUtil.dip2px(35), -DensityUtil.dip2px(2.5f),Gravity.RIGHT|Gravity.TOP);
        }
        linearLayoutComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
                editTextInput.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        editTextInput.setFocusable(true);
                        editTextInput.setFocusableInTouchMode(true);
                        editTextInput.requestFocus();
                        SoftInputUtil.showSoftInput(DynamicDetailActivity.this, editTextInput);
                    }
                },200);
            }
        });
        linearLayoutUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
                likeDynamic(mDynamicBean.getId(),"赞".equals(textView.getText()));
            }
        });
    }

    private void commentDynamic(int dynamic,int userId, String content) {
        WPHSdk.getService(BusinessService.class).commentDynamic(dynamic, userId, content, new YRequestCallback<List<CommentBean>>() {
            @Override
            public void onSuccess(List<CommentBean> var1) {
                mDynamicBean.setReplyList(var1);
                RxBus.getInstance().send(SubscriptionBean.createSendBean(RxEventType.UPDATE_DYNAMIC,mDynamicBean));
                if (mDynamicBean.getCommentCount() == 0 && mDynamicBean.getThumbUpCount() == 0) {
                    linearLayoutCommentArea.setVisibility(View.GONE);
                }else {
                    linearLayoutCommentArea.setVisibility(View.VISIBLE);
                }
                if (mDynamicBean.getCommentCount() > 0) {
                    listViewComment.setDatas(mDynamicBean);
                }
            }

            @Override
            public void onFailed(int var1, String message) {
                ToastManager.getInstance().showToast(message);
            }

            @Override
            public void onException(Throwable var1) {
                var1.printStackTrace();
            }
        });
    }

    private void likeDynamic(int dynamicId, boolean like) {
        WPHSdk.getService(BusinessService.class).addOrCancelLike(dynamicId, like, new YRequestCallback<List<ThumbUpBean>>() {
            @Override
            public void onSuccess(List<ThumbUpBean> var1) {
                mDynamicBean.setLikeList(var1);
                RxBus.getInstance().send(SubscriptionBean.createSendBean(RxEventType.UPDATE_DYNAMIC,mDynamicBean));
                if (mDynamicBean.getThumbUpCount() > 0) {
                    mLayoutLikeArea.setVisibility(View.VISIBLE);
                }else {
                    mLayoutLikeArea.setVisibility(View.GONE);
                }
                textViewUpUser.setText(mDynamicBean.getThumbUpStr());
            }

            @Override
            public void onFailed(int var1, String message) {

            }

            @Override
            public void onException(Throwable var1) {
                var1.printStackTrace();
            }
        });
    }

    private void deleteComment(int commentId) {
        WPHSdk.getService(BusinessService.class)
                .deleteComment(commentId, new YRequestCallback<List<CommentBean>>() {
                    @Override
                    public void onSuccess(List<CommentBean> var1) {
                        mDynamicBean.setReplyList(var1);
                        RxBus.getInstance().send(SubscriptionBean.createSendBean(RxEventType.UPDATE_DYNAMIC,mDynamicBean));
                        if (mDynamicBean.getCommentCount() == 0 && mDynamicBean.getThumbUpCount() == 0) {
                            linearLayoutCommentArea.setVisibility(View.GONE);
                        }else {
                            linearLayoutCommentArea.setVisibility(View.VISIBLE);
                        }
                        if (mDynamicBean.getCommentCount() > 0) {
                            listViewComment.setDatas(mDynamicBean);
                        }
                    }

                    @Override
                    public void onFailed(int var1, String message) {

                    }

                    @Override
                    public void onException(Throwable var1) {

                    }
                });
    }

    private void showDeleteDialog(final int commentId) {
        View view = LayoutInflater.from(DynamicDetailActivity.this).inflate(R.layout.view_pwin_delete_comment, null);
        final YunShlPopupWinow winow = new YunShlPopupWinow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        winow.setCommonConfig(DynamicDetailActivity.this, YunShlPopupWinow.AnimaDirect.DIRECT_BOTTOM_TOP);
        TextView textViewDelete = (TextView) view.findViewById(R.id.tv_delete);
        TextView textViewCancel = (TextView) view.findViewById(R.id.tv_cancel);
        textViewCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (winow != null) {
                    winow.dismiss();
                }
            }
        });
        textViewDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (winow != null) {
                    winow.dismiss();
                }
                deleteComment(commentId);
            }
        });
        winow.showAtLocation(DynamicDetailActivity.this.findViewById(R.id.root_view), Gravity.BOTTOM,0,0);
    }


    /**
     * 接管Activity的setExitSharedElementCallback
     * @param activity
     */
    public void setSharedElementCallback(Activity activity){
        ActivityCompat.setExitSharedElementCallback(activity, new SharedElementCallback() {
            @Override
            public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
                if (mReenterState!=null){
                    int index = mReenterState.getInt("index",0);
                    sharedElements.clear();
                    sharedElements.put("tansition_view",imageViewContent.getViewByIndex(index));
                    mReenterState = null;
                }
            }
        });

    }
    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        super.onActivityReenter(resultCode, data);
        mReenterState = new Bundle(data.getExtras());
    }
}
